package cn.kgc.springmvc03.controller;

import cn.kgc.springmvc03.entity.User;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/8
 * @Description:  springmvc中如何操作session和cookie
 *
 * @SessionAttribute("username")
 * @CookieValue("ck")
 *
 */
@RestController
@RequestMapping("user")
public class UserController {


    //  1.HttpSession session  2.HttpServletRequest request
    @RequestMapping("login")
    public Map login(User user, HttpServletRequest request , HttpServletResponse  response) {

        HashMap<String, Object> map = new HashMap<>();

        String username = user.getUsername();
        String password = user.getPassword();
        if("tom".equals(username)&&"123456".equals(password)){  //  登录成功
            // 如何实现将用户信息存入 session
            HttpSession session = request.getSession();

            Cookie cookie = new Cookie("ck", "ckValue");
            response.addCookie(cookie);

            session.setAttribute("username", user.getUsername());
            map.put("code",200);
            map.put("msg","登录成功");
        }else {   // 登录失败
            map.put("code",500);
            map.put("msg","用户名或密码错误");
        }
        return map;
    }

    //1.HttpSession session  2.@SessionAttribute("username")   参数  存入session时的key
    // 2. 获取cookie中的值  @CookieValue("ck")
    @RequestMapping("delete")
    public Map delete(Integer id,@SessionAttribute("username") String username,@CookieValue("ck") String cookeValue) {

        //String attribute = (String) session.getAttribute("username");
        //System.out.println(" session attribute = " + attribute);

        System.out.println("id = " + id);
        System.out.println("username = " + username);

        System.out.println("cookeValue = " + cookeValue);


        HashMap<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","删除成功");

        return map;
    }


    @RequestMapping("update")
    public Map update(User user){


        String str = null;
        str.toUpperCase();

        HashMap<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","更新成功");

        return map;
    }


}
